package com.example.texted.controller;

import com.example.texted.templatemethod.MyKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

@Controller
public class FileDController {
    @Autowired
    private MyKey myKey;

    @RequestMapping("hello")
    @ResponseBody
    public String hello() {
        String downUrl = "D:/keycode.csv";
        File file = new File( downUrl);
        if (!file.exists()) {
            return "404";
        }
        BasicFileAttributes bAttributes = null;
        try {
            bAttributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(bAttributes==null){
            return "无最后修改时间";
        }
        return file.getName()+" "+ DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(bAttributes.lastModifiedTime().toInstant());
    }
    @RequestMapping("key")
    @ResponseBody
    public String key() {
        return myKey.getSingKey();
    }
    /**
     * 附件下载
     *
     * @param request
     * @param response
     */
    @GetMapping("/down")
    public void downloadFileTwo(HttpServletRequest request, HttpServletResponse response) {
        String downUrl = "D:/keycode.csv";
        goToDownload(request, response, downUrl);
    }

    /**
     * 下载
     *
     * @param request
     * @param response
     * @param downUrl  下载的路径
     */
    private void goToDownload(HttpServletRequest request, HttpServletResponse response, String downUrl) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-msdownload");
        File file = new File( downUrl);
        if (!file.exists()) {
            try {
                response.sendError(404, "File not found!");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        String fileName = file.getName();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            String encodeNickName = URLEncoder.encode(fileName,"UTF-8");//转Unicode不然ie会乱码
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(encodeNickName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
            long fileLength = file.length();
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {//优雅
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
